package models

import (
	"errors"
	"fmt"
	"reflect"
	"strings"

	"github.com/beego/beego/v2/client/orm"
)

type Users struct {
	UserId        int64 `orm:"auto"`
	Gender        int
	SubRegionId   int
	Status        int
	UpdateTime    int64
	Nick          string
	HeadImg       string
	Age           int
	FreeChatCount int
}

func init() {
	orm.RegisterModel(new(Users))
}

// AddUsers insert a new Users into database and returns
// last inserted UserId on success.
func AddUsers(m *Users) (userId int64, err error) {
	o := orm.NewOrm()
	userId, err = o.Insert(m)
	return
}

// GetUsersByUserId retrieves Users by UserId. Returns error if
// UserId doesn't exist
func GetUsersByUserId(userId int64) (v *Users, err error) {
	o := orm.NewOrm()
	v = &Users{UserId: userId}
	if err = o.QueryTable(new(Users)).Filter("user_id", userId).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

func ExistUserByUserId(userId int64) (exist bool) {
	o := orm.NewOrm()
	exist = o.QueryTable(new(Users)).Filter("user_id", userId).RelatedSel().Exist()
	return
}

// GetAllUsers retrieves all Users matches certain condition. Returns empty list if
// no records exist
func GetAllUsers(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Users))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Users
	qs = qs.OrderBy(sortFields...).RelatedSel()
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateUsers updates Users by Id and returns error if
// the record to be updated doesn't exist
func UpdateUsersByUserId(m *Users) (err error) {
	o := orm.NewOrm()
	v := Users{UserId: m.UserId}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		//var num int64
		if _, err = o.Update(m); err != nil {
			return err
		}

	}
	return
}

func UpdateUsersByUserIdAndFields(m *Users, fields []string) (err error) {
	o := orm.NewOrm()
	v := Users{UserId: m.UserId}
	// ascertain id exists in the database
	err = o.Read(&v)
	if err == nil {
		//var num int64
		if _, err = o.Update(m, fields...); err != nil {
			return
		}
	}

	return
}

// 免费聊天次数递减
func DecrementUsersFreeChatCount(userId int64, value int) (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf("UPDATE users SET free_chat_count = free_chat_count - ? WHERE user_id = ?")
	_, err = o.Raw(sql, value, userId).Exec()
	if err != nil {
		return err // 返回错误信息给调用者
	}
	return nil // 明确返回nil表示无错误
}

// 免费聊天次数递增
func IncrementUsersFreeChatCount(userId int64, value int) (err error) {
	o := orm.NewOrm()
	sql := fmt.Sprintf("UPDATE users SET free_chat_count = free_chat_count + ? WHERE user_id = ?")
	_, err = o.Raw(sql, value, userId).Exec()
	if err != nil {
		return err // 返回错误信息给调用者
	}
	return nil // 明确返回nil表示无错误
}

// 修改用户字段值，例如增加或减少某个数值字段的值
func ModifyUserFieldValue(userId int64, field string, value int, operator string) (err error) {
	o := orm.NewOrm()
	sql := ""
	if operator == "-" {
		sql = fmt.Sprintf("UPDATE users SET %s = %s - ? WHERE user_id = ?", field, field)
	} else {
		sql = fmt.Sprintf("UPDATE users SET %s = %s + ? WHERE user_id = ?", field, field)
	}

	_, err = o.Raw(sql, value, userId).Exec()
	if err != nil {
		return err // 返回错误信息给调用者
	}
	return nil // 明确返回nil表示无错误
}

func TxUpdateUsersByUserIdAndFields(tx orm.TxOrmer, m *Users, fields []string) (err error) {
	// 使用传入的事务对象进行更新操作
	//var num int64
	if _, err = tx.Update(m, fields...); err != nil {
		// 使用日志库进行输出（假设已引入并初始化了日志库）
		//log.Printf("Number of records updated in database: %d", num)
		return err
	}
	return err
}

// DeleteUsers deletes Users by UserId and returns error if
// the record to be deleted doesn't exist
func DeleteUsers(userId int64) (err error) {
	o := orm.NewOrm()
	v := Users{UserId: userId}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		//var num int64
		if _, err = o.Delete(&Users{UserId: userId}); err != nil {
			return err
		}
	}
	return
}
